package com.lgx.common.dao.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.basic.dao.GeneralJdbcDao;
import com.lgx.common.dao.IImageDao;
import com.lgx.common.entity.Image;
import com.lgx.common.exception.DataException;
import com.lgx.common.web.util.FileUtils;

/**
 * 
 * @author acer
 *
 */
@Component
public class ImageDao extends GeneralDao implements IImageDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private GeneralJdbcDao baseDao;
	
	public GeneralJdbcDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(GeneralJdbcDao baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	@Transactional
	public Image createImage(Image image) throws DataException {
		this.getHibernateTemplate().save(image);
		log.info("[新增图片]:"+image.getId());
		return image;
	}

	@Override
	@Transactional
	public Image updateImage(Image image) throws DataException {
		this.getHibernateTemplate().update(image);
		log.info("[更新图片]:"+image.getId());
		return image;
	}

	@Override
	@Transactional
	public void deleteImage(Image image) throws DataException {
		log.info("[删除图片]:"+image.getId());
		if(!StringUtils.isEmpty(image.getFilePath()))FileUtils.fileDelete(image.getFilePath());
		this.getHibernateTemplate().delete(image);
	}

	@Override
	public void deleteImage(String id) throws DataException {
		this.deleteImage(this.findImageById(Long.parseLong(id)));
	}

	@Override
	public Image findImageById(long id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(Image.class, id);
	}

	@Override
	@Transactional
	public void deleteImageByFilePath(String filePath) throws DataException {
		String sql = "delete from ts_image where filepath = '"+filePath+"'";
		log.info("[删除图片]:"+filePath);
		if(!StringUtils.isEmpty(filePath))FileUtils.fileDelete(filePath);
		baseDao.getJdbcTemplate().execute(sql);
	}

}
